<template>
  <div class="container">
    <!-- 商品分类面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/goods' }">商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
        <!-- 搜索及新增商品区域 -->
        <el-row :span="24">
            <el-col :span="8">
              <!-- 输入框 -->
              <el-input clearable placeholder="请输入您需要查询的商品名称..." v-model="seachGoodsInputVal" @input="handleSearchInput" @clear="handleSearchClear" @keyup.enter.native="handleSearchEnter">
                <!-- 确认搜索按钮 -->
                <el-button slot="append" icon="el-icon-search" @click="handleSearchEnter"></el-button>
              </el-input>
            </el-col>
            <el-col :span="6">
              <!-- 添加商品按钮 -->
              <el-button type="primary"  class="marginL" @click="$router.push('/goods/addgood')">点击 新增商品</el-button>
            </el-col>
        </el-row>
        <!-- 表格展示商品区域 -->
        <template>
          <el-table
            :data="tableGoodsListData.goods"
            stripe
            border
            style="width: 100%">
            <el-table-column
            type="index"
            align="center">
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              prop="goods_name"
              label="商品名称"
              header-align="center">
            </el-table-column>
            <el-table-column
              prop="goods_price"
              label="商品价格"
              header-align="center"
              width="112">
              <template slot-scope="scope">
                <el-tag
                  type=""
                  size="mini"
                  effect="plain">
                  {{ `￥ ${scope.row.goods_price.toFixed(2)} 元` }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              prop="goods_number"
              header-align="center"
              width="100"
              label="商品数量">
              <template slot-scope="scope">
                <el-tag
                  type="warning"
                  size="mini"
                  effect="plain">
                  {{`剩余 ${scope.row.goods_number} 件`}}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              prop="goods_weight"
              header-align="center"
              align="center"
              width="80"
              label="单件重量">
              <template slot-scope="scope">
                <el-tag
                  type="info"
                  size="mini"
                  effect="plain">
                  {{`${scope.row.goods_weight} g`}}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              prop="goods_state"
              header-align="center"
              align="center"
              width="90"
              label="商品状态">
              <template slot-scope="scope">
                <el-tag
                  v-if="scope.row.goods_state === 0"
                  type="danger"
                  size="mini"
                  effect="plain">
                  未通过
                </el-tag>
                <el-tag
                  v-else-if="scope.row.goods_state === 1"
                  type="warning"
                  size="mini"
                  effect="plain">
                  审核中
                </el-tag>
                <el-tag
                  v-else
                  type="success"
                  size="mini"
                  effect="plain">
                  已通过
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              prop="is_promote"
              header-align="center"
              align="center"
              width="90"
              label="热销程度">
              <template slot-scope="scope">
                <el-tag
                  v-if="!scope.row.is_promote"
                  type="danger"
                  size="mini"
                  effect="plain">
                  当季热销
                </el-tag>
                <el-tag
                  v-else
                  type="info"
                  size="mini"
                  effect="plain">
                  即将下架
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              prop="add_time"
              header-align="center"
              align="center"
              width="160"
              label="创建日期">
              <template slot-scope="scope">
                {{scope.row.add_time | dateFormat}}
              </template>
            </el-table-column>
            <el-table-column
              prop="upd_time"
              header-align="center"
              align="center"
              width="160"
              label="更新时间">
              <template slot-scope="scope">
                {{scope.row.upd_time | dateFormat}}
              </template>
            </el-table-column>
            <el-table-column
              label="商品操作"
              align="center"
              width="120"
              header-align="center">
              <template slot-scope="scope">
                <el-button type="warning" icon="el-icon-edit" size="mini" @click="handleEditGoodInfo(scope.row)"></el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDelGood(scope.row)"></el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
        <!-- 分页器区域 -->
        <template>
          <div class="block">
            <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="getPageParams.pagenum"
              :page-sizes="[10, 15, 25, 30]"
              :page-size="getPageParams.pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="tableGoodsListData.total">
            </el-pagination>
          </div>
        </template>
    </el-card>
    <!-- 修改当前商品Dialog弹出对话框 -->
    <el-dialog title="编辑商品当前商品信息" :visible.sync="editGoodFormBool">
      <el-form :model="currentGoodData" ref="currentGoodFormRef" :rules="currentGoodInfoDataRules" label-position="right" label-width="100">
        <el-form-item label="修改商品名称" prop="goods_name" label-width="110px">
          <el-input v-model="currentGoodData.goods_name" placeholder="请输入需要更改的商品名称..." autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="修改商品价格" prop="goods_price"  label-width="110px">
          <el-input v-model.number="currentGoodData.goods_price" placeholder="请输入新的的商品价格..." autocomplete="off">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="修改商品库存" prop="goods_number" label-width="110px">
          <el-input v-model.number="currentGoodData.goods_number" placeholder="请更新最新的商品库存..." autocomplete="off">
            <template slot="append">件</template>
          </el-input>
        </el-form-item>
        <el-form-item label="修改单件重量" prop="goods_weight" label-width="110px">
          <el-input v-model.number="currentGoodData.goods_weight" placeholder="请更新商品重量..." autocomplete="off">
              <template slot="append">克</template>
          </el-input>
        </el-form-item>
        <el-form-item label="修改商品描述" prop="goods_introduce">
          <el-input v-model="currentGoodData.goods_introduce" placeholder="请输入更新对商品的描述..." show-word-limit maxlength="150" resize="none" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editGoodFormBool = false">取 消</el-button>
        <el-button type="primary" @click="editGoodFormSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'GoodList',
  created () {
    // 调用获取商品列表初始化数据
    this.getGoodsListData()
  },
  data () {
    return {
      // 搜索商品商品input表单数据双绑
      seachGoodsInputVal: '',
      // 展示商品页码及显示条数请求参数
      getPageParams: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      // 表格展示商品数据源
      tableGoodsListData: {},
      // 编辑当前商品信息弹出框
      editGoodFormBool: false,
      // 服务器获取当前商品详情信息数据
      currentGoodInfoServe: {},
      // 服务器商品详情数据用于判断与用户数据是否相等优化减少请求
      GoodDataServe: {
        goods_name: '',
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_introduce: ''
      },
      // 当前表单商品详情数据用于数据提交编辑当前商品信息
      currentGoodData: {
        goods_name: '',
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_introduce: ''
      },
      // 当前商品ID
      currentGoodID: 0,
      // 当前商品自定义验证规则
      currentGoodInfoDataRules: {
        goods_name: [
          { required: true, message: '商品名称信息必须填写...', trigger: 'blur' },
          { min: 1, message: '商品名称不得少于10个字符...', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '商品价格信息必须填写...', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '商品库存信息必须填写...', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '商品重量信息必须填写...', trigger: 'blur' }
        ],
        goods_introduce: [
          { max: 150, message: '商品描述信息不得超过150个字符...', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 请求获取商品数据初始化信息
    async getGoodsListData () {
      const { data: res } = await this.$http.get('goods', { params: this.getPageParams })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.tableGoodsListData = res.data
    },
    // 分页器当前页发生变化处理函数
    handleCurrentChange (val) {
      this.getPageParams.pagenum = val
      this.getGoodsListData()
    },
    // 分页器页码范围变化处理函数
    handleSizeChange (val) {
      this.getPageParams.pagesize = val
      this.getGoodsListData()
    },
    // 搜索框clearble清空触发
    handleSearchClear () {
      this.getPageParams.query = ''
      this.getGoodsListData()
    },
    // 搜索框实时查询
    handleSearchInput () {
      this.getPageParams.query = this.seachGoodsInputVal
      this.getGoodsListData()
    },
    // 搜索框当确认按键抬起、点击搜索按钮触发
    handleSearchEnter () {
      if (this.seachGoodsInputVal.trim().length === 0) {
        this.$notify({
          title: '温馨提示',
          message: '搜索框内容不允许为空！',
          type: 'warning',
          offset: 100
        })
      }
      this.getPageParams.query = this.seachGoodsInputVal
      this.getGoodsListData()
    },
    // 编辑当前商品弹出对话框
    async handleEditGoodInfo (curentGoodInfo) {
      console.log(curentGoodInfo.goods_id)
      if (!curentGoodInfo.goods_id) return this.$message.info('商品数据异常，请稍后重试！')
      const { data: res } = await this.$http.get(`goods/${curentGoodInfo.goods_id}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.currentGoodID = res.data.goods_id
      this.GoodDataServe = { ...res.data }
      this.currentGoodData = { ...res.data }
      this.editGoodFormBool = true
    },
    // 删除当前商品
    async handleDelGood (curentGoodInfo) {
      const confirmRes = await this.$confirm(`确认要将【${curentGoodInfo.goods_name}】商品所有信息删除吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmRes !== 'confirm') return this.$message.info(`【${curentGoodInfo.goods_name}】商品删除操作被终止！`)
      const { data: res } = await this.$http.delete(`goods/${curentGoodInfo.goods_id}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.getGoodsListData()
      this.$message.success(res.meta.msg)
    },
    // 提交商品修改---------------------------------------------------------------------------------------------
    editGoodFormSubmit () {
      this.$refs.currentGoodFormRef.validate(async valid => {
        if (!valid) return this.$message.info('表单存在不合法信息，请更正后重新提交！')
        const goodServeDataStr = JSON.stringify(this.GoodDataServe)
        const goodCurrentDataStr = JSON.stringify(this.currentGoodData)
        if (goodServeDataStr === goodCurrentDataStr) {
          this.$notify.warning({
            title: '商品信息未修改',
            message: '请修改商品信息后再进行提交，无需修改直接关闭！',
            offset: 200
          })
          return
        }
        const { data: res } = await this.$http.put(`goods/${this.currentGoodID}`, this.currentGoodData)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.getGoodsListData()
        this.editGoodFormBool = false
        this.$message.success(res.meta.msg)
      })
    }
  }
}
</script>

<style lang="less" scoped>
/* 面包屑区域 */
.el-breadcrumb {
    margin-bottom: 12px;
}
/* 卡片区域 */
.el-card {
    /* 表格区域 */
    .el-table {
      margin: 16px 0;
    }
}

/* 信息输入框高度 */
/deep/.el-textarea__inner {
  height: 120px!important;
}
/deep/ .el-input__count{
  margin-right: 20px;
  margin-bottom: -2px;
}

/* 设置外边距16px */
.marginL {
    margin-left: 16px;
}
</style>
